package com.leeyu.rabbitmq.headers;

import com.leeyu.rabbitmq.util.RabbitMQConnectionUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class PublisherTest {

    public static final String HEADER_EXCHANGE = "header-exchange";
    public static final String HEADER_QUEUE = "header-queue";

    @Test
    public void publish() throws Exception {
        // 获取连接
        Connection connection = RabbitMQConnectionUtil.getConnection();

        // 构建channel
        Channel channel = connection.createChannel();

        // 构建队列：
        // 设置交换机类型为Header
        channel.exchangeDeclare(HEADER_EXCHANGE, BuiltinExchangeType.HEADERS);

        // 构建队列
        channel.queueDeclare(HEADER_QUEUE, true, false, false, null);

        //交换机和队列的绑定参数，不需要路由键通过参数匹配
        Map<String, Object> arguments = new HashMap<>();
        // 匹配所有条件才会路由消息
        // arguments.put("x-match","all");
        // 匹配任意条件路由消息
        arguments.put("x-match","any");
        arguments.put("name","abc");
        arguments.put("value","123");
        channel.queueBind(HEADER_QUEUE, HEADER_EXCHANGE, "", arguments);

        // 发送消息
        HashMap<String, Object> headers = new HashMap<>();
        headers.put("name","abc");
        AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                .headers(headers).build();
        String message = "Header Letter!";
        channel.basicPublish(HEADER_EXCHANGE, "", props, message.getBytes(StandardCharsets.UTF_8));
    }

}
